<template>
	<view :style="{height: `${height}rpx`,overflow: 'hidden'}" class="cx-input">
		<view v-if="renameFocus === false" @tap="viewClick" class="view-input">
			<text v-if="!isShowPlaceholder()">{{insVal}}</text>
			<text v-if="isShowPlaceholder()" class="u-tips-color">{{placeholder}}</text>
		</view>
		<input class="real-input" ref="realInput" :type="type" v-if="renameFocus === true" v-model="insVal" :focus="true"
			:selection-start="start" :placeholder="placeholder" :selection-end="end" @input="onInput" @blur="onBlur" />
	</view>
</template>

<script>
	export default {
		name: "cx-input",
		props: {
			value: {
				type: [String, Number]
			},
			/**
			 * 输入框类型
			 */
			type: {
				type: String,
				default: "text"
			},
			placeholder: {
				type: String
			},
			/**
			 * 高度
			 */
			height: {
				type: Number,
				default: 40
			},
			disabled: {
				type: Boolean
			}
		},
		watch: {
			"value": {
				handler(val) {
					this.insVal = val
				},
				immediate: true
			}
		},
		data() {
			return {
				insVal: "",
				start: -1,
				end: -1,
				renameFocus: false
			}
		},
		methods: {
			isShowPlaceholder() {
				if (this.insVal === null || this.insVal === undefined) return true
				return false
			},
			viewClick() {
				if (!this.disabled) {
					const insVal = this.insVal
					this.renameFocus = true
					this.start = 0
					this.end = (insVal !== null && insVal !== undefined) ? insVal.toString().length : 0
					// #ifdef H5
					this.$nextTick(_ => {
						this.$refs.realInput.select()
					})
					// #endif
				}
			},
			onInput() {
				this.$emit("input", this.insVal)
			},
			onBlur() {
				this.renameFocus = false
				this.start = -1
				this.end = -1
				this.$emit("blur", this.insVal)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.cx-input {
		.view-input {
			width: 100%;
			height: 100%;
			font-size: 14px;
			display: flex;
			align-items: center;
		}
		.real-input {
			width: 100%;
			height: 100%;
			border: none;
			outline: none;
			background: none;
			font-size: 14px;
			padding: 0;
			margin: 0;
		}
	}
</style>